/**
 * 生产环境重新部署后，提示用户刷新页面
 */

import { ElMessageBox } from 'element-plus'
let lastSrcs; // 上一次获取到的script地址

const scriptReg = /\<script.*src=["'](?<src>[^"']+)/gm;

async function extractNewScripts () {
    const html = await fetch('/?_timestamp=' + Date.now()).then(res => res.text());
    scriptReg.lastIndex = 0;
    let result = [];
    let match;
    while ((match = scriptReg.exec(html))) {
        result.push(match.groups.src);
    }
    return result;
}
async function needUpdate () {
    const newScripts = await extractNewScripts();
    if (!lastSrcs) {
        lastSrcs = newScripts;
        return false;
    }
    let result = false;
    if (lastSrcs.length !== newScripts.length) {
        result = true;
    }
    for (let i = 0; i < lastSrcs.length; i++) {
        if (lastSrcs[i] !== newScripts[i]) {
            result = true;
            break;
        }
    }
    lastSrcs = newScripts;
    return result;
}
const DURATION = 10 * 1000;
function autoRefresh () {
    setTimeout(async () => {
        const willUpdate = await needUpdate()
        if (willUpdate) {
            ElMessageBox.alert('页面有更新，点击确定刷新页面', '提示', {
                confirmButtonText: '确定',
                callback: () => {
                    location.replace('http://localhost:3333/#/home')
                },
            })
        }
        autoRefresh()
    }, DURATION)
}
autoRefresh()